package org.example.rsy.web;


import org.example.rsy.exception.TikaException;
import org.example.rsy.service.ITikaService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/tika")
public class TikaController {


    private final Map<Integer, ITikaService> tikaServiceMap;

    public TikaController(List<ITikaService> tikaServices) {
        tikaServiceMap = new HashMap<>();
        tikaServices.forEach(s -> tikaServiceMap.put(s.getCode(), s));
    }

    @PostMapping("/parse")
    public String parse(@RequestParam MultipartFile file,
                        @RequestParam int code) {

        try {
            if (tikaServiceMap.containsKey(code)) {
                return tikaServiceMap.get(code).parse(file.getInputStream());
            }
            return null;
        } catch (IOException | TikaException e) {
            return e.getMessage();
        }
    }
}
